package com.duanruan.bmgl.controller;

import com.duanruan.bmgl.common.JsonData;
import com.duanruan.bmgl.entity.Department;
import com.duanruan.bmgl.entity.DepartmentVo;
import com.duanruan.bmgl.service.DepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 部门管理控制层
 *
 * @author makejava
 * @since 2020-08-21 12:10:24
 */
@RestController
@RequestMapping("/departments")
public class DepartmentController {

    @Resource(name = "departmentServicebmgl")
    private DepartmentService departmentService;

    /**
     *    多条件查询部门信息
     *    id--部门id
     *    name--部门名字
     *    type--部门类型
     *    page--当前页码
     *    limit--每页页数
     */
    @GetMapping
    public JsonData getDepartments(HttpServletRequest request){
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String type=request.getParameter("type");
        int page=Integer.parseInt(request.getParameter("page"));
        int limit=Integer.parseInt(request.getParameter("limit"));
        PageHelper.startPage(page,limit);
        List<Department> departments=departmentService.findDepartments(id,name,type);
        PageInfo<Department> pageInfo=new PageInfo<>(departments);
        int totalnums=(int)pageInfo.getTotal();
        int totalpages=pageInfo.getPages();
        DepartmentVo departmentVo=new DepartmentVo()
                .setPage(page).setLimit(limit).setTotalnums(totalnums)
                .setTotalpages(totalpages).setDepartmentList(departments);
        return JsonData.success("查询成功",departmentVo);
    }

    /**
     *   插入新部门信息
     *   -1代表id已存在，0代表插入失败，1代表插入成功
     */
    @PostMapping
    public JsonData insertDepartment(@RequestBody Department department){
        int num=departmentService.insertDepartment(department);
        if(num==-1) return JsonData.fail("插入失败,id已存在");
        else if(num==0) return JsonData.fail("插入失败");
        return JsonData.success("插入成功");
    }

    /**
     *  修改部门信息
     */
    @PutMapping
    public JsonData putDepartment(@RequestBody Department department){
        int num=departmentService.updateDepartment(department);
        if(num==1) return JsonData.success("修改成功");
        else return JsonData.fail("修改失败");
    }

    /**
     *  根据id删除部门
     *  -1代表部门下有员工，0代表删除失败，1代表删除成功
     */
    @DeleteMapping("/{id}")
    public JsonData deleteDepartment(@PathVariable int id){
        int num=departmentService.deleteDepartment(id);
        if(num==-1) return JsonData.fail("该部门下有员工不能删除");
        else if(num==0) return JsonData.fail("删除失败");
        return JsonData.fail("删除成功");
    }

}